package myJs.user

import myJs.Utils._
import myJs.myPkg.jquery._
import scalatags.Text.all._

import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation._
import myJs.Implicits._
import myJs.myPkg.{ColumnOptions, Select2Options, TableOptions}
import myJs.tool.Tool
import org.scalajs.dom.Element
import org.scalajs.dom.ext.Ajax
import shared.VarTool

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 2019/3/6
 */
@JSExportTopLevel("DataDetail")
object DataDetail {
  val tableId = "table"
  val headerMap = VarTool.headerMap
  val fieldNames = VarTool.totalFieldNames.filterNot { x =>
    List("barcode", "sampleName", "treeCode").contains(x)
  }

  @JSExport("init")
  def init = {
    refreshBasicInfo(getBarcode)
    initTable
    refreshTableView
    refreshGene
    //    refreshTable()

  }

  def refreshGene = {
    val inputName = "refGene"
    val url = g.jsRoutes.controllers.userC.DataController.getAllRefGeneByBarcode().url.toString
    Ajax.get(url = s"${url}?barcode=${getBarcode}").map { xhr =>
      val data = xhr.responseText.toJArS
      val array = (data).map { v =>
        js.Dictionary("text" -> v, "id" -> v)
      }
      val options = Select2Options.dictData(array.toJSArray)
      Tool.getInputByName(inputName).select2(options).trigger("onchange")
    }
  }

  @JSExport("geneChange")
  def geneChange(y: Element) = {
    val myValue = $(y).find(">option:selected").`val`().toString
    geneChangeByValue(myValue)
  }

  def geneChangeByValue(myValue: String) = {
    val gene = myValue
    val index = layer.load(1, Tool.layerOptions.shade(js.Array("0.1", "#fff")))
    val url = g.jsRoutes.controllers.userC.DataController.getAllDataByBarcodeAndRefGene().url.toString
    Ajax.get(url = s"${url}?barcode=${getBarcode}&refGene=${gene}").map { xhr =>
      val rs = xhr.responseText.toJArJDS
      $(s"#${tableId}").bootstrapTable("load", rs)
      layer.close(index)
    }
  }

  def refreshTable(f: JArJDS => js.Any = (myData) => ()) = {
    val url = g.jsRoutes.controllers.userC.DataController.getAllDataByBarCode().url.toString
    Ajax.get(url = s"${url}?barcode=${getBarcode}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJArJDS
      $(s"#${tableId}").bootstrapTable("load", rs)
      f(rs)
    }
  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case _ => v
  }

  def refreshTableView = {
    val names = fieldNames
    val nameMap = names.map { x =>
      (x -> headerMap.getOrElse(x, x))
    }
    val html = nameMap.map { case (field, name) =>
      label(marginRight := 15,
        input(`type` := "checkbox", checked, value := field, onclick := s"Utils.setColumns('${field}','${tableId}')", name)
      )
    }.mkString
    $("#checkbox").html(html)
    val hideColumns = names.drop(6)
    hideColumns.foreach { x =>
      $("#table").bootstrapTable("hideColumn", x)
      $(s"input:checkbox[value='${x}']").attr("checked", false)
    }
  }

  def initTable = {
    val table = tableId
    val columnNames = fieldNames
    val columns = columnNames.map { columnName =>
      val title = headerMap.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      ColumnOptions.field(columnName).title(title).sortable(true).formatter(fmt)
    }
    val options = TableOptions.columns(columns.toJSArray)
    $(s"#${tableId}").bootstrapTable(options)
  }

  def getBarcode = {
    g.barcode.toString
  }

  def refreshBasicInfo(barcode: String) = {
    val url = g.jsRoutes.controllers.userC.DataController.getDataByBarcode().url.toString
    Ajax.get(url = s"${url}?barcode=${barcode}").map { xhr =>
      val dict = JSON.parse(xhr.responseText).toJDS
      dict.foreach { case (k, v) =>
        $(s"#basicInfo #${k}").text(v.toString)
      }
    }
  }

}
